import { ref } from 'vue'
import { defineStore } from 'pinia'
import { local } from '@/utils/storage'

export const useSiteStore = defineStore('site', () => {
  const siteState = ref({
    showBanner: true,
    showBlurModel: false,
    currTheme: local.getItem('theme') || 'light', // light or dark
    theme: local.getItem('theme') || 'light',
  })

  _init()

  const setState = (key, val) => (siteState.value[key] = val, _recordState())
  const getTheme = () => siteState.value.theme
  const setTheme = theme => setState('theme', theme)
  const setShowBanner = v => setState('showBanner', v)

  const _reset = () => {
    siteState.value.theme = ''
    local.delItem('siteState')
  }

  function _init() {
    const state = JSON.parse(local.getItem('siteState'))
    if (state) Object.assign(siteState.value, state)
  }

  function _recordState() {
    local.setItem('siteState', JSON.stringify(siteState.value))
  }

  return {
    siteState,
    setTheme,
    getTheme,
    setShowBanner,
    setShowBlurModel: v => setState('showBlurModel', v),
    _reset
  }
})